<?php
/**
 * Created by JetBrains PhpStorm.
 * User: abdelrahman
 * Date: 7/6/13
 * Time: 10:09 AM
 * To change this template use File | Settings | File Templates.
 */

class Connection
{
    /**@var PDO */
    public $connection;

    /**
     * @param string $dsn
     * @param string $user
     * @param string $pass
     */
    public function __construct($dsn = 'mysql:host=localhost;dbname=el7a2ny;charset=utf8',
                                $user = 'dbuser',
                                $pass = 'ce3000feed')
    {
        $this->connection = new PDO($dsn, $user, $pass,
            array(PDO::ATTR_PERSISTENT => true,
                PDO::ATTR_AUTOCOMMIT => true,
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));

    }

    /**
     * @param string $stmt
     * @return PDOStatement
     */
    public function prepare($stmt)
    {
        return $this->connection->prepare($stmt);
    }

    /**
     * @return int
     */
    public function last_insert()
    {
        return $this->connection->lastInsertId();
    }

    /**
     * @param string $proc_name
     * @param array $params
     */
    public static function execProc($proc_name, $params = null)
    {
        $conn = new Connection();
        $stmt = null;
        if ($params == null)
        {
            $stmt = $conn->prepare("CALL " . $proc_name . "();");
            $stmt->execute();
        }
        else
        {
            $string = "CALL " . $proc_name . "(";
            $len = count($params);
            for ($i = 1; $i <= $len; $i++)
            {
                $string .= "?";
                if ($i != $len)
                    $string .= ",";
            }
            $string .= ");";
            $stmt = $conn->prepare($string);
            $stmt->execute($params);
        }
    }

    /**
     * @param string $func_name
     * @param array $params
     * @return mixed
     */
    public static function execFunc($func_name, $params = null)
    {
        $conn = new Connection();
        $stmt = null;
        if ($params == null)
        {
            $stmt = $conn->prepare("SELECT " . $func_name . "() as ret;");
            $stmt->execute();
        }
        else
        {
            $string = "SELECT " . $func_name . "(";
            $len = count($params);
            for ($i = 1; $i <= $len; $i++)
            {
                $string .= "?";
                if ($i != $len)
                    $string .= ",";
            }
            $string .= ") as ret;";
            $stmt = $conn->prepare($string);
            $stmt->execute($params);
        }
        $row = $stmt->fetch();
        return $row['ret'];
    }

}

?>